package org.drools.examples.templates;  
  
import java.util.ArrayList;  
  
import org.drools.template.DataProviderCompiler;  
import org.kie.api.KieServices;  
import org.kie.api.builder.KieBuilder;  
import org.kie.api.builder.KieFileSystem;  
import org.kie.api.builder.Message.Level;  
import org.kie.api.builder.model.KieBaseModel;  
import org.kie.api.builder.model.KieModuleModel;  
import org.kie.api.runtime.KieContainer;  
import org.kie.api.runtime.KieSession;  
  
/** 
 * 
 * Drools模板实例应用 
 *  
 */  
public class DataProviderCompilerTest {  
  
    public static void main(String[] args) {  
        ArrayList<String[]> rows = new ArrayList<String[]>();  
        rows.add(new String[] { "1", "status == 0" });  
  
        MyDataProvider tdp = new MyDataProvider(rows);  
        DataProviderCompiler converter = new DataProviderCompiler();  
        String drl = converter.compile(tdp, "/rules/rule_template_1.drl");  
  
        System.out.println(drl);  
  
        KieServices kieServices = KieServices.Factory.get();  
        KieModuleModel kieModuleModel = kieServices.newKieModuleModel();
  
        KieBaseModel baseModel = kieModuleModel.newKieBaseModel("FileSystemKBase").addPackage("rules");
        baseModel.newKieSessionModel("FileSystemKSession");  
        KieFileSystem fileSystem = kieServices.newKieFileSystem();  
  
        String xml = kieModuleModel.toXML();  
        System.out.println(xml);
        fileSystem.writeKModuleXML(xml); 

        fileSystem.write("src/main/resources/rules/rule1.drl", drl);  
  
        KieBuilder kb = kieServices.newKieBuilder(fileSystem);  
        kb.buildAll();
        if (kb.getResults().hasMessages(Level.ERROR)) {  
            throw new RuntimeException("Build Errors:\n" + kb.getResults().toString());  
        }  

        KieContainer kContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId());  
  
        KieSession kSession = kContainer.newKieSession("FileSystemKSession");  
  
        Message message = new Message();  
        message.setMessage("Hello World");  
        message.setStatus(Message.HELLO);  
  
        kSession.insert(message);  
        kSession.fireAllRules();  
        kSession.dispose();    
    }  
}  

